﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using LevenBlog.Core.Utils;

namespace LevenBlog.Core.Mvc
{
    public class SkinManager
    {
        /// <summary>
        /// 模板所在真实根目录
        /// </summary>
        public string RootPath { get; set; }
        /// <summary>
        /// 模板所在虚拟目录
        /// </summary>
        public string VisualRootPath { get; set; }

        public SkinManager()
            : this(string.Empty, string.Empty)
        {
        }

        public SkinManager(string rootPath, string visualRootPath)
        {
            RootPath = rootPath;
            VisualRootPath = visualRootPath;
        }

        public IList<SkinEntity> Get()
        {
            IList<SkinEntity> skins = new List<SkinEntity>();
            if (!Directory.Exists(RootPath))
                return skins;
            DirectoryInfo root = new DirectoryInfo(RootPath);
            DirectoryInfo[] sdir = root.GetDirectories();
            foreach (DirectoryInfo dir in sdir)
            {
                if (System.IO.File.Exists(RootPath.AppendPath(dir.Name).AppendPath("skin.xml")))
                {
                    SkinEntity skin = Get(RootPath.AppendPath(dir.Name).AppendPath("skin.xml"), dir.Name);
                    if (skin != null)
                        skins.Add(skin);
                }
            }
            return skins;
        }

        /// <summary>
        /// 获取指定路径的skinxml信息
        /// </summary>
        /// <param name="path">该路径为文件绝对路径</param>
        /// <returns></returns>
        public SkinEntity Get(string path,string vpath)
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
            using (fs)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(fs);
                SkinEntity skin = new SkinEntity();
                try
                {
                    skin.Designer = doc.SelectSingleNode("LevenBlogSkin/Designer").InnerText;
                    skin.Image = doc.SelectSingleNode("LevenBlogSkin/Image").InnerText;
                    skin.Mail = doc.SelectSingleNode("LevenBlogSkin/Mail").InnerText;
                    skin.Name = doc.SelectSingleNode("LevenBlogSkin/Name").InnerText;
                    skin.Path = vpath;
                    skin.PublicDate = Convert.ToDateTime(doc.SelectSingleNode("LevenBlogSkin/PublicDate").InnerText);
                    skin.Url = doc.SelectSingleNode("LevenBlogSkin/Url").InnerText;
                    return skin;
                }
                catch
                {
                    return null;
                }
            }
        }
    }
}
